package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortMode;
import com.ruoyi.net.domain.ElementSrNeighb;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortEth;
import com.ruoyi.net.service.IElementPortEthService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-以太网Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-以太网")
@RestController
@RequestMapping("/element/port/eth")
public class ElementPortEthController extends BaseController {
    @Autowired
    private IElementPortEthService elementPortEthService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    @ApiOperation(value = "读取网元-接口-以太网列表 init", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:eth:list')")
    @GetMapping("/init")
    public AjaxResult init(ElementPortEth elementPortEth) {
        elementPortEthService.init(elementPortEth);
        return AjaxResult.success();
    }
    /**
     * 读取网元-接口-以太网列表
     */
    @ApiOperation(value = "读取网元-接口-以太网列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:eth:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortEth elementPortEth) {

        List<ElementPortEth> elementPortEths = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>ETH-PHY</type>" +
                        "        <enabled>enable</enabled>" + // 主接口
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortEth.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortEth entity = new ElementPortEth();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setPortName(getXmlLabelValue(node, "name"));
                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
                    entity.setPortDesc(getXmlLabelValue(node, "description"));
                    Node ethOption = getXmlLabelNode(node, "eth-option");
                    if (ethOption != null) {
                        entity.setMac(getXmlLabelValue(ethOption, "mac-address"));
                    }
                    Node ethphyInterface = getXmlLabelNode(node, "ethphy-interface");
                    if( ethphyInterface != null) {
                        entity.setTerminalSpeedType(getXmlLabelValue(ethphyInterface, "speed"));
                        entity.setFiberOrCopper(getXmlLabelValue(ethphyInterface, "port-media-type"));
                        entity.setWorkMode(getXmlLabelValue(ethphyInterface, "negotiation-enable"));
                    }
                    entity.setTerminalMode(getXmlLabelValue(node, "transport-layer"));
                    entity.setMbps(getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    if (ipNode !=null) {
                        entity.setMaxFrameLen(getXmlLabelValue(ipNode, "ipv4-mtu"));
                        Node ipv4AddressListNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                        if (ipv4AddressListNode != null) {
                            String ip = getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                            entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                            entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
                            entity.setIpForm(getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                        }
                    }
                    Node vlanNode = getXmlLabelNode(node, "switched-vlan-cfg");
                    if (vlanNode != null) {
                        Node switchedNode = getXmlLabelNode(vlanNode, "switched-tpids");
                        entity.setVlan(getXmlLabelValue(switchedNode, "tpid"));
                    }
                    entity.setStatus("0"); // 从设备读取到的配置，设置状态为激活
//                    entity.setStatus("enable".equals(getXmlLabelValue(ethphyInterface, "negotiation-enable"))?"1":"0"); // 从设备读取到的配置，设置状态为激活
                    elementPortEths.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortEths);
    }

    /**
     * 查询网元-接口-以太网列表
     */
    @ApiOperation(value = "查询网元-接口-以太网列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:eth:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortEth elementPortEth) {
        startPage();
        List<ElementPortEth> list = elementPortEthService.selectElementPortEthList(elementPortEth);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-以太网列表
     */
    @ApiOperation(value = "导出网元-接口-以太网列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:eth:export')")
    @Log(title = "网元-接口-以太网", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortEth elementPortEth) {
        List<ElementPortEth> list = elementPortEthService.selectElementPortEthList(elementPortEth);
        ExcelUtil<ElementPortEth> util = new ExcelUtil<ElementPortEth>(ElementPortEth.class);
        util.exportExcel(response, list, "网元-接口-以太网数据");
    }

    /**
     * 获取网元-接口-以太网详细信息
     */
    @ApiOperation(value = "获取网元-接口-以太网详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:eth:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortEthService.selectElementPortEthById(id));
    }

    /**
     * 新增网元-接口-以太网
     */
    @ApiOperation(value = "新增网元-接口-以太网", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:eth:add')")
    @Log(title = "网元-接口-以太网", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortEth elementPortEth) {
        return toAjax(elementPortEthService.insertElementPortEth(elementPortEth));
    }

    /**
     * 修改网元-接口-以太网
     */
    @ApiOperation(value = "修改网元-接口-以太网", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:eth:edit')")
    @Log(title = "网元-接口-以太网", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortEth elementPortEth) {
        return toAjax(elementPortEthService.updateElementPortEth(elementPortEth));
    }

    /**
     * 删除网元-接口-以太网
     */
    @ApiOperation(value = "删除网元-接口-以太网", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:eth:remove')")
    @Log(title = "网元-接口-以太网", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortEthService.deleteElementPortEthByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortEth entity = elementPortEthService.selectElementPortEthById(id);
        entity.setStatus("1");
        if (sendXml(entity)) {
            return toAjax(elementPortEthService.updateElementPortEth(entity));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortEth entity = elementPortEthService.selectElementPortEthById(id);
        entity.setStatus("0");
        if (sendXml(entity)) {
            return toAjax(elementPortEthService.updateElementPortEth(entity));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortEth entity) {
        boolean isSend = false;
        // TODO: 2024/11/28  设备联调，添加并激活
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            StringBuilder xml = new StringBuilder();
            if ("1".equals(entity.getStatus())) {
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"create\">" +
                        "        <name>" + entity.getPortName() + "</name>" +
                        "        <type>ETH-PHY</type>" +
                        "        <enabled>enable</enabled>");
                if (StringUtils.isNotEmpty(entity.getPortDesc())) {
                    xml.append("        <description>" + entity.getPortDesc() + "</description>");
                }
                xml.append("        <eth-option xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-common\">" +
                        "          <loop-block>disable</loop-block>");
                //2.11修改：比对验收项 2.11文档 无该节点，暂时先注释
//                if (StringUtils.isNotEmpty(entity.getMac())) {
//                    xml.append("        <mac-address>" + entity.getMac() + "</mac-address>");
//                }
                xml.append("        </eth-option>");
                xml.append("        <ethphy-interface xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-phy\">" +
                        "          <up-holdtime>200</up-holdtime>" +
                        "          <down-holdtime>0</down-holdtime>" +
                        "          <tp-mode-enable>disable</tp-mode-enable>" +
                        "          <port-laser-startup-delay-time>0</port-laser-startup-delay-time>");// +
//                        "          <energy-saving-mode>disable</energy-saving-mode>" +
//                    "          <speed>" + entity.getTerminalSpeedType() + "</speed>" +
//                    "          <port-media-type>" + entity.getFiberOrCopper() + "</port-media-type>" +
//                    "          <negotiation-enable>" + entity.getWorkMode() + "</negotiation-enable>" +
                        //"          <negotiation-enable>disable</negotiation-enable>" +
                           if(StringUtils.isEmpty(entity.getWorkMode())) {
                               xml.append("          <negotiation-enable>disable</negotiation-enable>");
                           }
                           else  {
                               xml.append("          <negotiation-enable>" + entity.getWorkMode() + "</negotiation-enable>");
                           }
                       xml.append("        </ethphy-interface>");
                if (StringUtils.isNotEmpty(entity.getTerminalMode())) {
                    xml.append("        <transport-layer xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getTerminalMode() + "</transport-layer>");
                }
                // ----start   L3 三层属性IP配置 ---
//                    "        <bandwidth xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" + entity.getMbps() + "</bandwidth>" +
                xml.append("        <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                        "          <ipv4-mtu>" + (StringUtils.isEmpty(entity.getMaxFrameLen()) ? 1500 : entity.getMaxFrameLen()) + "</ipv4-mtu>");
                if (StringUtils.isNotEmpty(entity.getIp()) && StringUtils.isNotEmpty(entity.getMask())) {
                    xml.append("           <ipv4-address-list>" +
                            "               <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                            "               <secondry-use>mast</secondry-use>" + // entity.getIpForm()
                            "               </ipv4-address-list>");
                }
                xml.append("        </ip>");
                // ----end   L3 三层属性IP配置 ---
                //2.11修改：比对验收项 2.11文档 无该节点，暂时先注释
//                if (("enable".equalsIgnoreCase(entity.getVlanEnable()) || "1".equalsIgnoreCase(entity.getVlanEnable()) && StringUtils.isNotEmpty(entity.getVlan()))) {
//                    xml.append("        <qos-policy-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\"/>" +
//                            "        <switched-vlan-cfg xmlns=\"http://fiberhome.com/fhnw/yang/ethernetservice/fos-vlan\">" +
//                            "          <switched-tpids>" +
//                            "            <outer-tpid>" + entity.getVlan() + "</outer-tpid>" +
//                            "          </switched-tpids>" +
//                            "        </switched-vlan-cfg>");
//                }
                xml.append("      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
                isSend = deviceManager.editConfig(xml.toString(), "merge");
                logger.info("以太主接口激活xml：" + xml);
                xml = new StringBuilder();

                if ("1".equals(entity.getMplsEnable())) {
                    xml.append("<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                            "    <mpls-te>" +
                            "      <interface>" +
                            "        <ifname>" + entity.getPortName() + "</ifname>" +
                            "      </interface>" +
                            "    </mpls-te>" +
                            "  </mpls>");
                    isSend = deviceManager.editConfig(xml.toString(), "merge");
                    logger.info("以太主接口激活xml：" + xml.toString());
                }
            }
            else {
                // 去激活
                if ("1".equals(entity.getMplsEnable())) {
                    xml.append("<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                            "    <mpls-te>" +
                            "      <interface nc:operation=\"remove\">" +
                            "        <ifname>" + entity.getPortName() + "</ifname>" +
                            "      </interface>" +
                            "    </mpls-te>" +
                            "  </mpls>");
                    isSend = deviceManager.editConfig(xml.toString(), "merge");
                    logger.info("以太主接口激活xml：" + xml);
                    xml = new StringBuilder();
                }
                xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "        <interfaces>" +
                        "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "            <name>" + entity.getPortName() + "</name>" +
                        "            <type>ETH-PHY</type>" +
                        "            <enabled>enable</enabled>" +
                        "            <eth-option xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-common\">" +
                        "              <loop-block>disable</loop-block>" +
                        "            </eth-option>" +
                        "            <ethphy-interface xmlns=\"http://fiberhome.com/fhnw/yang/interface/ethinterface/fos-ethif-phy\" nc:operation=\"remove\"/>");
                if (StringUtils.isNotEmpty(entity.getIp()) && StringUtils.isNotEmpty(entity.getMask())) {
                    xml.append("        <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                            "           <ipv4-address-list nc:operation=\"remove\">" +
                            "               <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                            "               <secondry-use>mast</secondry-use>" + // entity.getIpForm()
                            "               </ipv4-address-list>" +
                            "        </ip>");

                }
                xml.append("          </interface>" +
                        "        </interfaces>" +
                        "      </if>");
                isSend = deviceManager.editConfig(xml.toString(), "merge");
                logger.info("以太主接口激活xml：" + xml.toString());
            }
        }
        return isSend;
    }
}